<template>
	<div ref="chartRef" :class="props.className" :style="{ height: props.height, width: props.width }" />
</template>

<script lang="ts" setup>
import { onActivated, onMounted, onBeforeUnmount, unref, ref, watch, nextTick} from 'vue';
import type { ECharts, EChartsOption } from 'echarts';
import * as echarts from 'echarts';
import theme from './theme.js';

const props = defineProps({
	// 自定义类名
	className: {
		type: String,
		required: false,
		default: '',
	},
	// 宽度
	width: {
		type: String,
		required: false,
		default: '100%',
	},
	// 高度
	height: {
		type: String,
		required: false,
		default: '100%',
	},
	// 配置参数
	options: {
		type: Object,
		required: true,
		default: undefined,
	}
});

const chartRef = ref<HTMLCanvasElement | null>(null);
let chart: ECharts | null = null;

watch(
	() => props.options,
	(options: EChartsOption | undefined) => {
		nextTick(() => {
			if (chart) {
				chart.setOption(options as EChartsOption, true);
			}
		});
	},
	{
		deep: true,
	}
);

const emits = defineEmits(['echartClick','echartOver','echartOut']);

onMounted(() => {
	// 设置异步，解决初始宽度问题
	nextTick(() => {
		initChart();
	});
});

echarts.registerTheme('theme', theme);

const initChart = (): void => {
	// 初始化echart
	const chartRefWrap = unref(chartRef);
	if (chartRefWrap) {
		chart = echarts.init(chartRefWrap);
		chart.on('click', (params: any) => {
			emits('echartClick', params);
		});
		chart.on('mouseover', (params: any) => {
			emits('echartOver', params);
		});
		chart.on('mouseout', (params: any) => {
			emits('echartOut', params);
		});
		chart.setOption(props.options as EChartsOption, true);
		window.addEventListener('resize', chartsResize);
	}
};

onActivated(() => {
	// 防止keep-alive之后图表变形
	if (chart) {
		nextTick(() => {
			chart.resize();
		});
	}
});

const chartsResize = () => {
	chart && chart.resize();
};

onBeforeUnmount(() => {
	window.removeEventListener('resize', chartsResize);
	chart = null;
});
</script>
   
